import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# 打开浏览器
service = Service(r'C:\Users\槲寄生\Downloads\chromedriver-win64\chromedriver-win64\chromedriver.exe')
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service, options=chrome_options)   # 创建浏览器对象

"""
需求：使用cookie实现跳过登录
1). 手动登录淘宝，获取cookie
2). 使用获取到的cookie，达到登录目的，然后就可以执行登录之后的操作
"""

# 1. 先访问淘宝页面，确保域名匹配（关键步骤）
driver.get("https://www.taobao.com")
time.sleep(2)  # 等待页面加载

# 2. 你的完整Cookie字符串
cookie_str = "thw=cn; cna=iOrXHxXDXjICAbSPLdsWPX5B; tracknick=t_1510555945735_0730; havana_lgc2_0=eyJoaWQiOjM1MDk4NzE3NDgsInNnIjoiMzc4MWY3ZWQzOGQyMWUyYTZkNDBhODc1NjI5Y2JhMjUiLCJzaXRlIjowLCJ0b2tlbiI6IjFIZl9qT3ZyUGpTaU9zM0JNX3QxbTdnIn0; _hvn_lgc_=0; cookie2=16eb55d5472f42beaa9026cb180892e4; t=a8ff41f84c8a9c65ddee26a58a5d0285; _tb_token_=737eb37e560a6; mtop_partitioned_detect=1; _m_h5_tk=1eb1ac0d0a90bfc4e34c157aa1523fca_1762273011069; _m_h5_tk_enc=2af27462c8ad9fc35f7b6b6b42a8e288; _samesite_flag_=true; unb=3509871748; uc1=cookie14=UoYY4dvffC28eg%3D%3D&pas=0&cookie15=U%2BGCWk%2F75gdr5Q%3D%3D&existShop=false&cookie16=VT5L2FSpNgq6fDudInPRgavC%2BQ%3D%3D&cookie21=U%2BGCWk%2F7p4mBoUyS4E9C; sn=; uc3=lg2=W5iHLLyFOGW7aA%3D%3D&nk2=F6k3HS2mUBl%2BZoMaA0IIyCEAGlY%3D&id2=UNX75JYoKfi6Qg%3D%3D&vt3=F8dD2kv%2F1yjsg5MyK58%3D; csg=822bd2ea; lgc=t_1510555945735_0730; cancelledSubSites=empty; cookie17=UNX75JYoKfi6Qg%3D%3D; dnk=t_1510555945735_0730; skt=a20f3bc5a8d699b9; existShop=MTc2MjI2MjU3Mw%3D%3D; uc4=id4=0%40UgJ%2BWH9aYVpkwNyix5GXk6ZFLiuT&nk4=0%40FbMocxjbpg28Xlfsxy%2B%2Ft5RHgGkevBec3bARsf%2B1wQ%3D%3D; _cc_=UIHiLt3xSw%3D%3D; _l_g_=Ug%3D%3D; sg=081; _nk_=t_1510555945735_0730; cookie1=B0P5CXby5HXMy8haNDJ%2FI7RDYcqqDu4ou%2FX1Ra4QswE%3D; wk_cookie2=185581eff005ea7bba9820e660d21c47; wk_unb=UNX75JYoKfi6Qg%3D%3D; sgcookie=E100n6W%2B3Mu8kNRqSR5e0pSYr76Db96EEf6UnPa8gDRcxiZ3ppOUme%2BNxRLHGow9LcuO96BYsXhFn9g%2Bzgw3zcoIsvLRFJbSI7iuS6cKTvafhkvhG%2BlU0xs1mxys1rmE%2FCfi; sdkSilent=1762291373782; havana_sdkSilent=1762291373782; xlly_s=1; havana_lgc_exp=1793366656926; fastSlient=1762262656926; isg=BDw8Q2X6ecbsPkeHsZq0JVkdDdruNeBfmaevsxa_RicK4d5rPkXc7qoSwQmZkhi3; tfstk=gd-E2QZumDnUQIPsACIz36LyE1SdXglfK315ELvld6f3AkNk7KdPOY3dAF5ysC53OMZB_4fMnYd5ApZy_Ld8Ae9CxgkyOCkdR2KyWuJveHMdVvIppgIoGjif4ppd2bKeeKtFjdXpITVlqVsGYkAaBjijcp3hpg9iGeTetJXlhujl-aVGI1BPKkfkZNjGE1qhEkXusAWRsgVlKwmgItWbrTAlqAJG6TjlKQboQdfOEgfoMpOXa2B5-A6AM5ZZAf71ipfaqoyALwcBIzZ7V3WF8pph_9Web97Fia5cCZ-H1LxBvN3Ylgp6uQ8kscreapYDZ6tiiu5WkTJl3imY31xeUh7p5W4h3M5FoHbghoJVrF-NAHc8kd9NtZS65VhCPMReksQnWfdyQ6OkYNVE1_TXCHbwifZwwa8HTOjc4-NRIQ-22ePuzwXOQsMZQPYy2fKCofkuyzQK8O5jKCa8ywXOQsMZQzURJ3WNGvA1."
# 3. 拆分Cookie字符串为独立键值对，逐个添加
for cookie_item in cookie_str.split('; '):
    # 分割key和value（处理value中可能包含=的情况）
    if '=' in cookie_item:
        key, value = cookie_item.split('=', 1)
        # 构造单个Cookie字典
        single_cookie = {
            'name': key,
            'value': value,
            'domain': '.taobao.com',  # 淘宝Cookie通用域名
            'path': '/',
            'httpOnly': False,  # 适配大部分淘宝Cookie
            'secure': False     # 非HTTPS环境也能生效
        }
        try:
            driver.add_cookie(single_cookie)
            print(f"成功添加Cookie: {key}")
        except Exception as e:
            # 部分Cookie可能因格式限制添加失败，不影响整体使用
            print(f"跳过Cookie {key}: {str(e)[:50]}")

# 4. 刷新页面使Cookie生效
time.sleep(3)
driver.refresh()
time.sleep(3)

# 5. 退出浏览器
driver.quit()
